import axios from 'axios';
import { handleApiError } from '@/utils/errorHandler';
import { useUserStore } from '@/store/user';

// 创建axios实例
const apiClient = axios.create({
  baseURL: import.meta.env.VITE_API_URL || 'http://localhost:5000/api',
  headers: {
    'Content-Type': 'application/json',
    'Accept': 'application/json'
  },
  timeout: 15000 // 默认请求超时时间为15秒
});

// 请求拦截器
apiClient.interceptors.request.use(
  (config) => {
    // 从store获取token
    const userStore = useUserStore();
    const token = userStore.token;
    
    // 如果有token则添加到请求头
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    
    return config;
  },
  (error) => {
    return Promise.reject(handleApiError(error));
  }
);

// 响应拦截器
apiClient.interceptors.response.use(
  (response) => {
    return response;
  },
  (error) => {
    const processedError = handleApiError(error);
    
    // 如果是401错误，可能是token过期，清除用户状态
    if (processedError.status === 401) {
      const userStore = useUserStore();
      userStore.logout();
    }
    
    return Promise.reject(processedError);
  }
);

// 用户API
export const userApi = {
  // 用户注册
  register: (userData) => {
    return apiClient.post('/users/register', userData);
  },
  
  // 用户登录
  login: (credentials) => {
    return apiClient.post('/users/login', credentials);
  },
  
  // 获取用户资料
  getProfile: () => {
    return apiClient.get('/users/profile');
  },
  
  // 更新用户资料
  updateProfile: (userData) => {
    return apiClient.put('/users/profile', userData);
  },
  
  // 修改密码
  changePassword: (passwordData) => {
    return apiClient.put('/users/password', passwordData);
  },
  
  // 获取用户书签
  getBookmarks: () => {
    return apiClient.get('/users/bookmarks');
  },
  
  // 添加书签
  addBookmark: (cardId) => {
    return apiClient.post('/users/bookmarks', { cardId });
  },
  
  // 删除书签
  removeBookmark: (cardId) => {
    return apiClient.delete(`/users/bookmarks/${cardId}`);
  },
  
  // 获取用户笔记
  getNotes: () => {
    return apiClient.get('/users/notes');
  },
  
  // 添加笔记
  addNote: (noteData) => {
    return apiClient.post('/users/notes', noteData);
  },
  
  // 更新笔记
  updateNote: (noteId, noteData) => {
    return apiClient.put(`/users/notes/${noteId}`, noteData);
  },
  
  // 删除笔记
  deleteNote: (noteId) => {
    return apiClient.delete(`/users/notes/${noteId}`);
  },
  
  // 获取学习进度
  getLearningProgress: () => {
    return apiClient.get('/users/progress');
  },
  
  // 更新学习进度
  updateProgress: (progressData) => {
    return apiClient.put('/users/progress', progressData);
  },
  
  // 获取学习报告
  getLearningReport: () => {
    return apiClient.get('/users/report');
  }
};

// 文档API
export const documentApi = {
  // 获取所有文档
  getAll: () => {
    return apiClient.get('/documents');
  },
  
  // 获取用户的所有文档
  getUserDocuments: () => {
    return apiClient.get('/documents');
  },
  
  // 获取单个文档
  getById: (id) => {
    return apiClient.get(`/documents/${id}`);
  },
  
  // 上传文档
  upload: (formData, config) => {
    return apiClient.post('/documents/upload', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      },
      timeout: 60000, // 上传文档超时时间设置为60秒
      ...config
    });
  },
  
  // 处理文档（生成卡片）
  process: (id) => {
    // 处理文档不设置超时时间，由后端决定处理时长
    return apiClient.post(`/documents/${id}/process`, {}, {
      timeout: 0 // 不设置超时时间
    });
  },
  
  // 从失败的地方继续处理文档
  reprocess: (id) => {
    // 不设置超时时间，由后端决定处理时长
    return apiClient.post(`/documents/${id}/reprocess`, {}, {
      timeout: 0 // 不设置超时时间
    });
  },
  
  // 删除文档
  delete: (id) => {
    return apiClient.delete(`/documents/${id}`);
  },
  
  // 更新文档信息
  update: (id, documentData) => {
    return apiClient.put(`/documents/${id}`, documentData);
  },
  
  // 获取文档的所有卡片
  getDocumentCards: (documentId) => {
    return apiClient.get(`/documents/${documentId}/cards`);
  },
  
  // 获取文档的章节列表
  getDocumentChapters: (documentId) => {
    return apiClient.get(`/documents/${documentId}/chapters`);
  },
  
  // 获取文档摘要（使用通义千问 Qwen-Long 模型）
  getDocumentSummary: (documentId) => {
    return apiClient.get(`/documents/${documentId}/summary`, {
      timeout: 120000 // 增加到120秒超时时间，因为AI处理可能需要较长时间
    });
  }
};

// 卡片API
export const cardApi = {
  // 获取所有卡片
  getAll: (params) => {
    return apiClient.get('/cards', { params });
  },
  
  // 获取单个卡片
  getById: (id) => {
    return apiClient.get(`/cards/${id}`);
  },
  
  // 获取文档的所有卡片
  getByDocument: (documentId, params) => {
    return apiClient.get(`/documents/${documentId}/cards`, { params });
  },
  
  // 获取相关卡片
  getRelated: (cardId) => {
    return apiClient.get(`/cards/${cardId}/related`);
  },
  
  // 更新卡片
  update: (id, cardData) => {
    return apiClient.put(`/cards/${id}`, cardData);
  },
  
  // 获取卡片章节列表
  getChapters: (documentId) => {
    return apiClient.get(`/documents/${documentId}/chapters`);
  },
  
  // 获取卡片标签列表
  getTags: (documentId) => {
    return apiClient.get(`/documents/${documentId}/tags`);
  },
  
  // 获取所有卡片标签
  getAllTags: () => {
    return apiClient.get('/cards/tags');
  }
};

// 练习题API
export const exerciseApi = {
  // 获取所有练习题
  getAll: (params) => {
    return apiClient.get('/exercises', { params });
  },
  
  // 获取卡片的练习题
  getByCard: (cardId) => {
    return apiClient.get(`/cards/${cardId}/exercises`);
  },
  
  // 获取文档的练习题
  getByDocument: (documentId, params) => {
    return apiClient.get(`/documents/${documentId}/exercises`, { params });
  },
  
  // 检查答案
  checkAnswer: (exerciseId, answer) => {
    return apiClient.post(`/exercises/${exerciseId}/check`, { answer });
  },
  
  // 生成新练习题
  generate: (cardId, options) => {
    return apiClient.post(`/cards/${cardId}/exercises/generate`, options);
  },
  
  // 获取练习统计
  getStats: () => {
    return apiClient.get('/exercises/stats');
  }
};

// 学习路径API
export const learningPathApi = {
  // 获取用户的学习路径
  getUserPaths: () => apiClient.get('/learning-paths/user'),
  
  // 获取学习路径详情
  getPathById: (id) => apiClient.get(`/learning-paths/${id}`),
  
  // 获取文档的学习路径
  getPathByDocument: (documentId) => apiClient.get(`/learning-paths/document/${documentId}`),
  
  // 生成学习路径
  generateLearningPath: (documentId) => apiClient.post(`/learning-paths/generate/${documentId}`),
  
  // 更新学习步骤状态
  updateStepProgress: (pathId, data) => apiClient.put(`/learning-paths/${pathId}/progress`, data),
  
  // 获取下一个学习步骤
  getNextStep: (pathId) => apiClient.get(`/learning-paths/${pathId}/next-step`)
};

// 学习报告
export const getLearningReport = async () => {
  return await apiClient.get('/users/report');
};

// 用户数据清理
export const cleanupUserData = async (dataType = 'all') => {
  return await apiClient.delete(`/users/data?dataType=${dataType}`);
};

// 获取用户统计数据
export const getUserStats = async () => {
  return await apiClient.get('/users/stats');
};

// 导出API客户端，方便直接使用
export default apiClient; 